package com.hmdp.ThreadUtil;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**


/**
 *@Author:fengxiaohui
 *@Description: 线程 操作 资源类
 *@Date:Create in 2:52 下午 2023/6/6
 *@Modified By:
 */
public class ThreadExample {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        //并发：多线程操作资源类，把资源类丢入到线程
        // @FunctionalInterface 函数式接口，jdk1.8 lambda表达式 (参数)->{ 代码 }
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"t1");
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"t2");
        Thread t3 = new Thread(()->{
            for (int i = 0; i < 20; i++) {
                ticket.sale();
            }
        },"t3");
        t1.start();
        t2.start();
        t3.start();


    }


}

// 资源类 OOP（面向对象）
//Lock接口锁
class Ticket {
    //属性、方法
    private int number = 50;
    Lock lock = new ReentrantLock();
    public void sale(){
        if (number > 1  ) {
            lock.lock();//加锁
            try{
                System.out.println(Thread.currentThread().getName() + "卖出了 "+ (number--) + "票，剩余： "+number  );
            }catch (Exception e){
                e.printStackTrace();
            }finally{
                lock.unlock();//释放锁
            }

        }
    }
}

